﻿/*
 * 由SharpDevelop创建。
 * 用户： LimitUser
 * 日期: 2013-1-16
 * 时间: 15:27
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using DotNet.Common;

namespace AdminRun
{
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{
#if DEBUG
			//args = new string[]{@"E:\A.安装文件\F.调试环境\Wix35.msi"};
			//args = new string[]{@"D:\App\ultradefrag\ultradefrag.exe"};
			//args = new string[]{@"C:\Documents and Settings\LimitUser\Application Data\Microsoft\Internet Explorer\Quick Launch\Revouninstaller.lnk"};
			//args = new string[]{@"C:\Program Files\VS Revo Group\Revo Uninstaller\Revouninstaller.exe"};
#endif			
			if(args.Length == 0)
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new MainForm());
			}
			else
			{
				OpenFileByAdmin(args);
			}
		}
		
		static void OpenFileByAdmin(string[] args)
		{
			Debug.Assert(args.Length > 0);
			
			string filePath = args[0];
			string exeArg = string.Empty;
			for(int index = 1;index < args.Length;index++)
			{
				exeArg = string.Format("{0} {1}",exeArg,args[index]);
			}
			
			string commandPath;
			if(ShellOpenCommand.ReadCommandPath(Path.GetExtension(filePath),out commandPath))
			{
				filePath = commandPath.Replace("%1",filePath);
				if(filePath.Contains("%*"))
				{
					filePath = filePath.Replace("%*",exeArg);
					exeArg = string.Empty;
				}
			}
			else
			{
				filePath = string.Format("\"{0}\"",filePath);
			}
			
			XMLConfig<AppData> data = new XMLConfig<AppData>();
			if(data.Load(Application.StartupPath + @"\appData.xml"))
			{
				if(!string.IsNullOrEmpty(data.Data.ExeFilepath))
			    {
					if(string.IsNullOrEmpty(exeArg))
					{
						exeArg = filePath;
					}
					else
					{
			   			exeArg = string.Format("{0} {1}",filePath,exeArg);
					}
			   		filePath = data.Data.ExeFilepath;
			    }
				if(!string.IsNullOrEmpty(data.Data.RunResult))
				{
					exeArg = data.Data.RunResult.Replace("\"<TargetPath>\"",exeArg);
					exeArg = exeArg.Replace("<WorkDir>",Path.GetDirectoryName(args[0]));
				}
			}
			
			CommonApp.RunWinExeFile(filePath,exeArg);
		}
	}
}
